from engine.user import UserModel
from Field import ContentField , ListField ,AuthorField ,IntegerField , StringField
from exts import all_logger
from tools.engine.cover_image import get_cover_image
from tools.engine.slug import get_slug
from mongodb_engine.database import DataBase
from app.config import DATALIST_BLOG , DATABASE_NAME1
class BlogModel:
    Mongodb_list : DataBase
    """
    self.title: 标题，长度 5 - 120 字符，必填
    self.author: 作者，引用 users 集合，必填
    self.slug: 网址标识，可由标题生成，必填
    self.content: 正文，最少 200 字符，必填
    self.summary: 摘要，最长 200 字符，无则截取正文
    self.category: 分类，可选值 “技术”“生活”“公告”“资源”，必填
    self.tags: 标签，字符串列表，最多 8 个，每个最长 20 字符
    self.status: 状态，可选值 “draft”“published”“archived”，必填
    self.created_at: 创建时间，自动记录当前时间
    self.updated_at: 更新时间，自动记录当前时间
    self.views: 浏览量，整数，最小为 0，初始 0
    self.likes: 点赞用户列表，引用 users 集合，初始为空
    self.comments: 评论列表，元素为字典，初始为空
    self.meta_description: 元描述，最长 160 字符
    self.cover_image: 封面图，需为合法 URL
    self.allow_comments: 评论开关，布尔类型

    """
    def __init__(
            self,
            title: str,
            author: UserModel,
            content: str,
            category: list,
            tags: list,
            #status: str = "draft",
            cover_image: str = None,
            slug: str = False,
            summary: str = None,
            allow_comments: bool = True,
            meta_description: str = None
    ):
        """初始化并进行字段验证"""
        try:

            # 核心元数据
            self.title = StringField(max_length=50, min_length=5, required=True).validate(title)
            self.author = AuthorField().validate(author)
            self.slug = get_slug(slug)

            # 内容相关
            self.content = ContentField().validate(content)
            # todo 预留修改简介的函数
            self.summary = StringField(max_length=200).validate(summary if summary else content[:197] + "...")

            # 分类系统
            self.category = ListField(max_elements=8).validate(category)
            self.tags = ListField(max_elements=4).validate(tags)

            # 状态控制 todo
           #  self.status = StringField(allowed_values=["draft", "published", "archived"], required=True).validate(status,"status")

            # 更新时间
            # self.created_at = DateTimeField(auto_now=True).validate()
            # self.updated_at = DateTimeField(auto_now=True).validate()

            # 互动数据
            self.views = IntegerField(min_value=0).validate(0)
            self.likes = ListField(max_elements=10000000).validate([])
            self.comments = ListField(max_elements=10000000).validate([])  # todo嵌套评论结构

            # SEO优化
            self.meta_description = StringField(max_length=160).validate(meta_description)
            self.cover_image = get_cover_image(cover_image)
            all_logger.info("博客创建成功")
        except ValueError as e:
            all_logger.error(f"博客创建失败: {str(e)}")
            raise ValueError(f"字段验证错误: {str(e)}")
        except Exception as e:
            all_logger.error(f"未知错误: {type(e)} - {str(e)}")
            raise Exception("博客创建失败")
    def database_config(self,data_name = DATABASE_NAME1 ,data_list = DATALIST_BLOG):
        self.Mongodb_list = DataBase(data_name,data_list)
    def save(self):
        try:
            self.database_config()
            self.Mongodb_list.insert(self.__dict__)
            all_logger.info("博客保存成功")
        except Exception as e:
            all_logger.error(f"博客保存失败: {str(e)}")
            raise Exception("博客保存失败")
    def update(self,data):
        try:
            self.database_config()
            self.Mongodb_list.update(data,self.slug)
            all_logger.info("博客更新成功")
        except Exception as e:
            all_logger.error(f"博客更新失败: {str(e)}")
            raise Exception("博客更新失败")

